package com.qfedu.aunt.commons.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.aunt.commons.auth.entity.SecurityUser;
import com.qfedu.aunt.commons.exception.BusinessException;
import com.qfedu.aunt.commons.mapper.UserMapper;
import com.qfedu.aunt.commons.pojo.Perm;
import com.qfedu.aunt.commons.pojo.Role;
import com.qfedu.aunt.commons.pojo.User;
import com.qfedu.aunt.commons.result.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaobobo
 * @title: MyUserDetailService
 * @projectName aunt_commons_2209
 * @description: TODO
 * @date 2022/10/31  10:25
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //这里按照逻辑来说是要通过用户名查询用户信息
        if(StringUtils.isEmpty(username)){
           throw new BusinessException(
                   ResponseCode.USERNAME_PASSWORD_EXCEPTION.getCode(),
                   ResponseCode.USERNAME_PASSWORD_EXCEPTION.getMessage());
        }
        //执行到这里 说明用户名对的

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        User user = userMapper.selectOne(userQueryWrapper);
        //判断下用户查询到没有
        if(null==user){
            throw new BusinessException(
                    ResponseCode.USERNAME_PASSWORD_EXCEPTION.getCode(),
                    ResponseCode.USERNAME_PASSWORD_EXCEPTION.getMessage());
        }
        //执行到这里 说用查询到了
        //查询角色和权限信息

        List<Role> roles=userMapper.findRolesByUserId(user.getUserId());
        List<Perm> perms=userMapper.findPermsByUserId(user.getUserId());

        List<String> authorityList=new ArrayList<>();
        for (Role r:roles) {
            authorityList.add("ROLE_"+r.getRoleName());
        }
        //接下来添加权限
        for (Perm p:perms) {
            authorityList.add(p.getPermVal());
        }

        SecurityUser securityUser = new SecurityUser();
        securityUser.setCurrentUserInfo(user);
        securityUser.setPermissionValueList(authorityList);

        return securityUser;
    }
}
